<template>
  <div class="Box">
    <div class="title">
        <h3>套餐管理</h3>
    </div>
    <div class="blackLine"></div>
    <div class="abilityBox" id="mealBox">
        <el-button type="primary" plain class="mealBtn" @click="openForm('add')">添加套餐</el-button>
        <div id="selectMealBox">
            <el-select id="select_meal" v-model="searchParam.categoryId" clearable placeholder="请选择">
                <el-option
                v-for="item in mealOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
        </div>
        <div id="mealSerName">
            <el-input v-model="searchParam.name" placeholder="请输入套餐名称"></el-input>
        </div>
        <el-button id="serIcon" icon="el-icon-search" size="mini" circle @click="findMealAll()"></el-button>
    </div>
    <div id="tableMealBox">
        <el-table
            :cell-class-name="tableCellClassName"
            :highlight-current-row="true"
            :stripe="true"
            :border="true"
            :data="tableData"
            style="width: 100%"
            >
            <el-table-column
                align="center"
                fixed
                prop="id"
                label="ID"
                width="150">
            </el-table-column>
            <el-table-column
                align="center"
                prop="categoryName"
                label="类别"
                width="100">
            </el-table-column>
            <el-table-column
                align="center"
                prop="name"
                label="套餐名称"
                width="150">
            </el-table-column>
            <el-table-column
                align="center"
                prop="price"
                label="价格"
                width="100">
            </el-table-column>
            <el-table-column
                align="center"
                prop="state"
                label="状态"
                width="100">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.state === 0? 'success':'danger'">{{scope.row.state == 0? '在售':'下架'}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="sort"
                label="排序"
                width="80">
            </el-table-column>
            <el-table-column
                prop="dishListName"
                label="内容"
                show-overflow-tooltip
                >
                <template slot-scope="scope">
                    <el-tag
                      size="small"
                      :key="tag.name"
                      v-for="tag in dishListName[scope.row.index]"
                      >
                      {{tag.name}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="120">
                <template slot-scope="scope">
                    <el-button
                        @click="openForm('edit',scope.row.id)"
                        type="text"
                        size="small">
                        编辑
                    </el-button>
                    <el-button
                        @click="deleteOneMeal(scope.row.id)"
                        type="text"
                        size="small">
                        移除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页 -->
    <div id="pageMealBox">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
        </el-pagination>
    </div>
    <!-- 表单弹窗 -->
    <el-dialog
        :show-close="false"
        :close-on-click-modal="false"
        :title="this.isEditForm == true ? '编辑套餐':'添加套餐'"
        :visible.sync="centerDialogVisible"
        width="40%"
        center>
        <el-form ref="form" :rules="rules" :model="formData" label-width="100px" size="mini">
            <el-form-item label="套餐名称：" prop="name">
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="选择类别：">
                <el-select v-model="formData.categoryId" placeholder="请选择" prop="categoryId">
                    <el-option
                      v-for="item in mealOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="套餐价格：">
                <el-input-number v-model="formData.price" :precision="2" controls-position="right" :min="0" :max="10000"></el-input-number>
            </el-form-item>
            <el-form-item label="套餐排序：">
                <el-input-number v-model="formData.sort" controls-position="right"  :min="0" :max="200" />
            </el-form-item>
            <el-form-item label="套餐状态：">
                <el-radio-group v-model="formData.state">
                    <el-radio :label='0'>在售</el-radio>
                    <el-radio :label='1'>停售</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="套餐内容：" prop="dishList">
                <el-cascader
                    :show-all-levels="false"
                    :emitPath="false"
                    v-model="formData.dishList"
                    placeholder="可搜索"
                    filterable
                    :options="dishOptions"
                    :props="props"
                    clearable>
                </el-cascader>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="colseForm()">取 消</el-button>
            <el-button type="primary" @click="doMeal('form')">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import router from '@/router';
export default {
    data() {
        //验证类别id是否为空
        var validateCategoryId = (rule, value, callback) =>{
            console.log(value)
            if ( value == '') {
                callback(new Error('请选择类别'))
            }else{
                callback();
            }
        }
        return {
            //表单验证
            rules: {
                name: [
                    { required: true,message: "名称不能为空" , trigger: 'blur'},
                    { min: 2, max: 10, message: "长度在 2 到 10个字符", trigger: "blur" },
                ],
                categoryId : [
                    // { validator: validateCategoryId,trigger: "blur"},
                    { required: true,message: "类别不能为空" , trigger: 'blur'}
                ],
                // dishList:[
                //     { required: true,message: "至少选择一项菜品",trigger: "blur"}
                // ]
            },
            //表单弹窗是否显现
            centerDialogVisible: false,
            //判断是编辑表单还是新增表单
            isEditForm: false,
            //表单数据
            formData:{
                name:'',
                categoryId: '',
                price: '',
                sort: '',
                state: 0,
                //套餐内容选择的菜品id
                dishList:[],
            },
            //选择套餐数组
            mealOptions: [],
            //开启选择器多选
            props: { multiple: true },
            //菜品选择器数组
            dishOptions: [
                // {
                //     value: 1,
                //     label: '肉类',
                //     children: [
                //             { value: 3, label: '普陀' },
                //             { value: 4, label: '黄埔' },
                //             { value: 5, label: '徐汇' }
                //     ]
                // }
            ],
            //表格数据
            tableData: [
                // {
                //     id: '1611930938293948417',
                //     categoryName: '节日套餐',
                //     name: '中秋宴',
                //     price: '300',
                //     state: 0,
                //     sort: 10,
                //     dishListName: [],
                // }, 
            ],
            //套餐内容数据
            dishListName:[
                // [
                //     {
                //         name:"1"
                //     },
                //     {
                //         name:"2"
                //     },
                // ],
                // [
                //     {
                //         name:"3"
                //     },
                //     {
                //         name:"4"
                //     },
                // ],
            ],
            //查找参数
            searchParam:{
                categoryId: '',
                name: '',
            },
            page:{
                //当前第几页
                currentPage: 1,
                //数据总条数
                total: 0,
                //每页条数
                pageSize: 10,
            }
        }
    },
    methods: {
        // 页面size改变
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.page.pageSize = val;
            this.findMealAll();
        },
        // 页面码数改变
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.page.currentPage = val;
            this.findMealAll();
        },
        //el表格的回调方法给索引赋值
        tableCellClassName({row, column, rowIndex, columnIndex}){
            row.index=rowIndex;
            column.index=columnIndex;
        },
        //查找tableData数据
        findMealAll(){
            this.$axios.post("http://localhost:8888/hwy/cater/meal/findMealAll/"+this.page.currentPage+"/"+this.page.pageSize,this.searchParam)
                    .then((response) => {
                        console.log(response)
                        this.tableData = response.data.data.finalList;
                        this.dishListName = response.data.data.dishListName;
                        this.page.total = response.data.data.page.total;
                        // console.log(this.dishListName[0])
                    })
        },
        //删除套餐(单)
        deleteOneMeal(id){
            this.$confirm("此操作将永久删除此套餐, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(()=>{
                this.$axios.post("http://localhost:8888/hwy/cater/meal/deleteOneMeal/"+id)
                    .then((response) => {
                        if (response.data.code === 1 ) {
                            this.$message({
                                message: response.data.data,
                                type: 'success',
                            });
                            this.findMealAll();
                        } else {
                            this.$message({
                                message: response.data.msg,
                                type: 'error',
                            });
                        }
                            this.findDish();
                    })
            }).catch(()=>{
                this.$message({
                    type: "info",
                    message: "已取消删除",
                });
            })
        },
        //清除FormData里面的数据
        clearFormData(){
            this.formData.name = '',
            this.formData.categoryId = '',
            this.formData.price = '',
            this.formData.sort = '',
            this.formData.state = 0,
            this.formData.dishList = []
            if (this.isEditForm == true) {//如果是编辑表单关闭，还需要清除这些数据
                this.formData.id = '';
                this.formData.createTime = '';
                this.formData.updateTime = '';
                this.formData.createUser = '';
                this.formData.updateuser = '';
            }
        },
        //打开弹窗
        openForm(type,id){
            if (type == "add") {
                // console.log("新增")
            } else if(type == 'edit') {
                // console.log("编辑")
                this.$axios.get("http://localhost:8888/hwy/cater/meal/getMealById/"+id)
                    .then((response) => {
                        console.log(response)
                        this.formData = response.data.data;
                    })
                this.isEditForm = true;
            } 
            this.centerDialogVisible = true;
        },
        //关闭弹窗
        colseForm(){
            this.clearFormData()
            this.centerDialogVisible = false;
            this.isEditForm = false;
        },
        //查询选择套餐数组的数据（即套餐数据）
        findDetailCategory(){
            this.$axios.post("http://localhost:8888/hwy/cater/category/findDetailCategory/2")
                    .then((response) => {
                        this.mealOptions = response.data.data;
                    })
        },
        //查询菜品选择器的数据
        findDishOptions(){
            this.$axios.get("http://localhost:8888/hwy/cater/dish/findDishOptions")
                    .then((response) => {
                        // console.log(response.data.data)
                        this.dishOptions = response.data.data;
                    })
        },
        //添加套餐或编辑套餐
        doMeal(ruleForm){
            // console.log(this.formData)
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    if (this.isEditForm == true) {
                        // console.log("编辑")
                        this.$axios.post("http://localhost:8888/hwy/cater/meal/editMeal",this.formData)
                            .then((response)=>{
                                if (response.data.code === 1 ) {
                                    this.$message({
                                        message: response.data.data,
                                        type: 'success',
                                    });
                                    this.colseForm();
                                    this.findMealAll();
                                } else {
                                    this.$message({
                                        message: response.data.msg,
                                        type: 'error',
                                    });
                                }
                            })
                    } else {
                        // console.log("添加")
                        this.$axios.post("http://localhost:8888/hwy/cater/meal/addMeal",this.formData)
                        .then((response) => {
                            this.$message({
                                message: response.data.data,
                                type: 'success',
                            });
                            this.colseForm();
                            this.findMealAll();
                        })
                    }
                } else {
                    this.$message({
                        message: '请输入正确信息。',
                        type: 'error'
                    });
                    return false;
                }
            })
            // this.colseForm();
        }
    },
    mounted() {
        this.findDetailCategory();
        this.findDishOptions();
        this.findMealAll()
    },
}
</script>

<style scoped>
@import '@/assets/css/eat/meal.css'
</style>